"""
321hello world good
444
"""

# 修改文件内容,把上面的good修改成bad


# 方法1:一次性把文件内的内容读到内存当中,然后再修改
"""
with open('gg.txt',mode='rt',encoding='utf-8') as f:
    res = f.read()
    data = res.replace('good','bad')

print(data,end='')
with open('gg.txt',mode='wt',encoding='utf-8') as ff:
    ff.write(data)
"""


# 方法2:把文件内容写进临时文件,这样占用的是磁盘文件,内存占用不是特别大
import os
from typing import no_type_check_decorator
with open('tmp.txt','wt',encoding='utf-8') as f,\
    open('gg.txt','rt',encoding='utf-8') as ff:
    for line in ff:
        data = line.replace('bad','good')
        f.write(data)

os.remove('gg.txt')
os.rename('tmp.txt','gg.txt')